package com.chengww.mylibrary;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chengww.mylibrary.adapter.BannerAdapter;
import com.chengww.mylibrary.base.BaseActivity;
import com.chengww.mylibrary.base.WrapContentLinearLayoutManager;
import com.chengww.mylibrary.bean.AllPics;
import com.chengww.mylibrary.bean.SimpleBean;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends BaseActivity {

    private File root;

    private ViewPager mViewPager;
    private TabLayout mTabLayout;

    //首页图片分类列表
    private List<View> viewArrayList;
    private List<String> mTitleList;



    @Override
    protected void onLoaded(Context context) {

    }

    @Override
    protected void onLoading(Context context) {
        root = new File(Environment.getExternalStorageDirectory(),"pics");

        viewArrayList = new ArrayList<>();
        mTitleList = new ArrayList<>();

        if (root.exists()){
            File[] categories = root.listFiles();
            if (categories != null && categories.length > 0){
                for (File category : categories) {
                    //分类
                    if (category.isDirectory()) {
                        File[] cate = category.listFiles();
                        for (File f : cate) {
                            if (f.isDirectory()){
                                bindPics(f);
                            }
                        }

                    }
                }
                //所有分类遍历完成
                mViewPager.setAdapter(new BannerAdapter(viewArrayList,mTitleList));
                mTabLayout.setupWithViewPager(mViewPager);
            }

        }
    }

    private void bindPics(File category) {
        List<List<File>> allPics = new ArrayList<>();

        mTitleList.add(category.getName());
        List<SimpleBean> beans = new ArrayList<>();
        //图片列表
        File[] picList = category.listFiles();
        if (picList != null && picList.length > 0) {
            for (File picDir : picList) {
                if (picDir.isDirectory()) {
                    File[] pics = picDir.listFiles();

                    SimpleBean bean = new SimpleBean();
                    List<String> tags = new ArrayList<>();
                    bean.setTags(tags);
                    beans.add(bean);
                    //图片列表名
                    String name = picDir.getName();
                    String regex="\\(.*?\\)|\\{.*?\\}|\\[.*?\\]|（.*?）";
                    Pattern p = Pattern.compile(regex);
                    Matcher m = p.matcher(name);
                    while(m.find()){
                        tags.add(m.group());
                    }

                    bean.setName(name.replaceAll(regex,""));
                    //时间
                    long time = picDir.lastModified();
                    Calendar cal = Calendar.getInstance();
                    cal.setTimeInMillis(time);
                    Date date = cal.getTime();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    bean.setTime(dateFormat.format(date));
                    //图片列表
                    List<File> images = new ArrayList<>();
                    allPics.add(images);

                    if (pics != null && pics.length > 0) {
                        //具体每一张图片
                        for (int j = 0; j < pics.length; j++) {
                            File pic = pics[j];
                            if (pic.isFile()) {
                                String picName = pic.getName();
                                String[] pattern = {".jpg",".jpeg",".png",".PNG",".bmp",".BMP",".gif",".GIF"};
                                for (String aPattern : pattern) {
                                    if (picName.endsWith(aPattern)) {
                                        images.add(pic);
                                        //第一个加入到预览图
                                        if (j == 0) {
                                            bean.setImage(pic);
                                        }
                                    }
                                }

                            }
                        }
                        //图片遍历完成
                        bean.setCount(images.size());
                    }
                }
            }
        }

        viewArrayList.add(initRecycler(beans,allPics));
    }

    private RecyclerView initRecycler(List<SimpleBean> beans,List<List<File>> pics) {
        RecyclerView mRecyclerView = new RecyclerView(this);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        SimpleAdapter adapter = new SimpleAdapter(beans,pics);
        adapter.bindToRecyclerView(mRecyclerView);
        return mRecyclerView;
    }

    @Override
    public void initParams(Bundle params) {

    }

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(View view) {
        setTitle(getResources().getString(R.string.app_name));

        mViewPager = $(R.id.view_pager);
        mTabLayout = $(R.id.tab_layout);
    }

    @Override
    public void widgetClick(View v) {

    }

    class SimpleAdapter extends BaseQuickAdapter<SimpleBean, BaseViewHolder> {

        private List<List<File>> pics;

        public SimpleAdapter(@Nullable List<SimpleBean> data,List<List<File>> pics) {
            super(R.layout.recycler_item_pic, data);
            this.pics = pics;
        }

        @Override
        protected void convert(final BaseViewHolder helper, SimpleBean item) {
            helper.setText(R.id.tv_title,item.getName())
                    .setText(R.id.tv_time,item.getTime())
                    .setText(R.id.tv_pics,"[" + item.getCount() + "P]");

            ImageView ima = helper.getView(R.id.image);
            Glide.with(MainActivity.this).load(item.getImage()).into(ima);

            CardView card_view = helper.getView(R.id.card_view);
            card_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AllPics allPics = AllPics.newInstance();
                    allPics.setPics(pics);
                    Bundle args = new Bundle();
                    args.putInt(PicsViewActivity.INDEX,helper.getAdapterPosition());
                    MainActivity.this.startActivity(PicsViewActivity.class,args);
                }
            });

            LinearLayout layout_tag = helper.getView(R.id.layout_tags);
            List<String> tags = item.getTags();
            if (tags != null && tags.size() > 0){
                for (int i = 0; i < tags.size(); i++) {
                    TextView textView = new TextView(MainActivity.this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    params.setMargins(6,0,6,0);
                    textView.setTextSize(10);
                    textView.setTextColor(getResources().getColor(android.R.color.white));
                    textView.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    textView.setPadding(6,4,6,4);
                    textView.setText(tags.get(i));
                    textView.setLayoutParams(params);
                    layout_tag.addView(textView);
                }

            }
        }
    }
}
